package com.zhima.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.zhima.service.CheckCodeService;
import com.zhima.service.PhoneService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import static com.zhima.constant.RedisConstant.*;

@Service
public class PhoneCheckCodeServiceImpl implements CheckCodeService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private PhoneService phoneService;

    @Override
    public String sendCheckCode(String address) {
        String checkCode = RandomUtil.randomNumbers(6);
        // 向手机发送验证码
        phoneService.send(address, String.format("{\"checkCode\":%s}", checkCode), "checkCode");
        // 将值保存到redis中，并设置有效期
        stringRedisTemplate.opsForValue().set(phoneCheckCodeKey(address), checkCode, CHECK_CODE_EXPIRE_TIME, CHECK_CODE_EXPIRE_TIME_UNIT);
        return checkCode;
    }

    @Override
    public String getCheckCode(String address) {
        return stringRedisTemplate.opsForValue().get(phoneCheckCodeKey(address));
    }
}
